package parsers;

import database.UserData;
import entity.Client;
import entity.DataObject;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import logger.LoggerManager;
import resurses.LoggerMessage;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by alexander.makalov on 22.10.2014.
 */
public class ClientJsonParser implements IParser {

    public String getPathToJsonFile() {
        return pathToJsonFile;
    }

    public void setPathToJsonFile(String pathToJsonFile) {
        this.pathToJsonFile = pathToJsonFile;
    }

    public ClientJsonParser() {
    }

    public ClientJsonParser(String path) {
        pathToJsonFile = path;
    }

    @Override
    public void startParsing() {
        LoggerManager.getLogger().Log(String.format(LoggerMessage.START_JSON_PARSING,pathToJsonFile), LoggerManager.LogLevel.INFO);
        if (pathToJsonFile != null) {
            try {
                FileReader reader = new FileReader(pathToJsonFile);
                JsonElement jelement = new com.google.gson.JsonParser().parse(reader);
                Gson gson = new Gson();
                LoggerManager.getLogger().Log(LoggerMessage.START_PARSING_FILE, LoggerManager.LogLevel.INFO);
                dataObject = gson.fromJson(jelement, DataObject.class);
                parseDataObjectToClient(dataObject.getData());
                UserData.setFileExist(true);
                LoggerManager.getLogger().Log(LoggerMessage.END_PARSING_FILE, LoggerManager.LogLevel.INFO);
            } catch (FileNotFoundException e) {
                LoggerManager.getLogger().Log(e.getMessage(), LoggerManager.LogLevel.ERROR);
                UserData.setFileExist(false);
                //e.printStackTrace();
            }catch (Exception e){
                LoggerManager.getLogger().Log(e.getMessage(), LoggerManager.LogLevel.ERROR);
                UserData.setFileExist(false);
            }
        }
    }

    @Override
    public List<Client> getClientsList() {
        return clientList;
    }

    public DataObject getDataObject() {
        return dataObject;
    }

    private void parseDataObjectToClient(List<List<String>> list){
        clientList = null;
        clientList = new ArrayList<>();
        for (int i = 0;i<list.size();i++){
            Client client = new Client();
            client.setName(list.get(i).get(0));
            client.setSurname(list.get(i).get(1));
            client.setPhone(list.get(i).get(2));
            client.setCity(list.get(i).get(3));
            client.setDescription(list.get(i).get(4));
            clientList.add(client);
        }
    }
    private String pathToJsonFile;
    private DataObject dataObject;
    private List<Client> clientList;
}
